import { constantRoutes } from '@/router';
import Layout from '@/layout'
import store from '@/store'
import getters from '@/store/getters'
import { asyncRouterMap, constantRouterMap } from '@/router'
var parent
var dataArray =[]

function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}
   /**
 *后台的路由表
 * asyncRouterMap
 */
export const componentsMap = {
    'permission1': () => import('@/views/permission/permission1/index'),
    'permission2': () => import ('@/views/permission/permission2/index'),
    'Table': () => import('@/views/table/index'),
    'complex-table':() => import('@/views/table/complex-table'),
    'Tree': () => import('@/views/tree/index'),
    'Form': () => import('@/views/form/index'),
    'Menu1':() => import('@/views/nested/menu1/index'),
    'Menu1-1':() => import('@/views/nested/menu1/menu1-1'),
    'Menu1-2':() => import('@/views/nested/menu1/menu1-2'),
    'Menu1-2-1':() => import('@/views/nested/menu1/menu1-2/menu1-2-1'),
    'Menu1-2-2':() => import('@/views/nested/menu1/menu1-2/menu1-2-2'),
    'Menu1-3':() => import('@/views/nested/menu1/menu1-3'),
    'Menu2':() => import('@/views/nested/menu2/index'),
    'commonUser': () => import ('@/views/commonUser/index')
    
}
      /**
 *将后台的路由表进行格式化
 * @param {*} asyncRouterMap
 */
function convertRouter(asyncRouterMap) {
    const accessedRouters = []
    asyncRouterMap = JSON.parse(asyncRouterMap);
    Recursion(asyncRouterMap)
    if(dataArray){
       for(var i =0;i<dataArray.length;i++){
          accessedRouters.push(dataArray[i])
       }
    }
    //accessedRouters=dataArray
    //accessedRouters[0].push({ path: '*', redirect: '/404', hidden: true })
    return accessedRouters
  }

  function Recursion(asyncRouterMap){
      asyncRouterMap.forEach(function (data){
         var sortParent = data.component
         if(sortParent == "Layout"){//根元素
            parent = generateRouter(data, true)//配置根元素
            dataArray.push(parent)
         }
         
      })
      return data2tree(asyncRouterMap,dataArray)
  }
   function data2tree(asyncRouterMap,dataArray){
       for(var j=0;j<dataArray.length;j++){
          var dataArrayIndex = dataArray[j]
          var childrenArray = []
          var sortIds = dataArrayIndex.id //父元素id
          for(var i=0;i<asyncRouterMap.length;i++){
             var data = asyncRouterMap[i]
             var parentId = asyncRouterMap[i].parentId  //当前元素的父级id
             if(parentId == sortIds){//判断是否为sortIds 子元素
                childrenArray.push(generateRouter(asyncRouterMap[i], false))
                dataArrayIndex.children = childrenArray
             }
             
          }
          if(childrenArray.length>0){
            data2tree(asyncRouterMap,childrenArray)  
          }
       }
       return dataArray
   }
  
    /**
 *后台的路由表
 * @param {*} asyncRouterMap  component的处理
 */
  function generateRouter(item, isParent) {
    var router = {
      path: item.path,
      name: item.name,
      meta: item.meta,
      parentId: isParent ? '': item.parentId,
      id: item.id,
      //component: isParent ? Layout : () => import(item.component)//获取组件的方法
      component: isParent ? Layout : componentsMap[item.name]
      
    }
     //console.log(router)
    return router
  }
  
const permission = {
    namespaced: true,
    state: {
        routers: constantRoutes,
        addRouters: []
    },
    mutations: {
      SET_ROUTERS: (state, routers) => {
        state.addRouters = routers;
        state.routers = constantRoutes.concat(routers);
      }
    },
    actions: {
        //前端根据后台传来的roles用户权限 判断本地asyncRouterMap路由
        // GenerateRoutes({ commit }, data) {
        //     return new Promise(resolve => {
        //         const { roles } = data;
        //         const accessedRouters = asyncRouterMap.filter(v => {
        //             if (hasPermission(roles, v)) {
        //                 if (v.children && v.children.length > 0) {
        //                     v.children = v.children.filter(child => {
        //                         if (hasPermission(roles, child)) {
        //                             return child
        //                         }
        //                         return false;
        //                     });
        //                     return v
        //                 } else {
        //                     return v
        //                 }
        //             }
        //             return false;
        //         });
        //         commit('SET_ROUTERS', accessedRouters);
        //         resolve();
        //     })
        // }
        //前端根据存于服务器上的asyncRouterMap路由 
        GenerateRoutes({ commit }, data) {
            return new Promise(resolve => {
            const { asyncRouterMap } = data
            const accessedRouters = convertRouter(asyncRouterMap)
            commit('SET_ROUTERS', accessedRouters)
            resolve()
            })
        }
  
    }
};
  
export default permission;